package com.example.ftp;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private FtpServer mFtpServer;
    private int port = 9999;// 端口号
    private String ftpConfigDir = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/ftpConfig/";
    private TextView tvHttp;
    private Button btnStart;
    private Button btnStop;
    private FtpServer server;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvHttp = findViewById(R.id.tv_http);
        btnStart = findViewById(R.id.btn_start);
        btnStop = findViewById(R.id.btn_stop);

        String info = "请通过浏览器或者我的电脑访问以下地址\n" + "ftp://" + getLocalIpAddress()
                + ":" + port + "\n";
        DebugLog.d(DebugLog.LOG + " info " + info);
        tvHttp.setText(info);

        initClick();
        request();
    }

    private void initClick() {
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File f = new File(ftpConfigDir);
                if (!f.exists())
                    f.mkdir();

                startFtpServer();

//                try {
//                    startFtp();
//                } catch (FtpException e) {
//                    e.printStackTrace();
//                }
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (server != null) {
                    server.stop();
                    server = null;
                }
            }
        });
        request();
    }

    private void request() {
        PermissionUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void onGranted() {
                copyResourceFile(R.raw.users, ftpConfigDir + "users.properties");
            }

            @Override
            public void onDenied(List<String> deniedPermissions) {

            }
        });
    }

    /**
     * 获取本地ip
     *
     * @return
     */
    public String getLocalIpAddress() {
        String strIP = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        strIP = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            DebugLog.e(DebugLog.LOG + " msg---" + ex.toString());
        }
        return strIP;
    }


    private void copyResourceFile(int rid, String targetFile) {
        InputStream fin = getResources().openRawResource(rid);
        FileOutputStream fos = null;
        int length;
        try {
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            while ((length = fin.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 启动ftp
     */
    public void startFtpServer() {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();

        String[] str = {"mkdir", ftpConfigDir};
        try {
            Process ps = Runtime.getRuntime().exec(str);
            try {
                ps.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = ftpConfigDir + "users.properties";
        File files = new File(filename);
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());

        factory.setPort(port);

        try {
            serverFactory.addListener("default", factory.createListener());
            server = serverFactory.createServer();
            this.mFtpServer = server;
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }

//        try {
//            serverFactory.addListener("default",factory.createListener());
//            FtpServer server = serverFactory.createServer();
//            this.mFtpServer = server;
//            server.start();
//        } catch (FtpException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (server != null) {
            server.stop();
            server = null;
        }
    }



}
